package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"database/sql"
	"github.com/go-ini/ini"            // 引入 ini 包
	_ "github.com/go-sql-driver/mysql" // MySQL 驱动
	_ "github.com/lib/pq"              // PostgreSQL 驱动
)

var PORT string

// 定义请求结构体，匹配 FreeSWITCH 发来的 JSON 数据格式
type EventRequest struct {
	SipNetworkIp   string                 `json:"sip_network_ip"`
	SipNetworkPort string                 `json:"sip_network_port"`
	Timestamp      string                 `json:"timestamp"`
	Event          string                 `json:"event"`
	Direction      string                 `json:"direction"`
	CallerNumber   string                 `json:"caller_number"`
	CallUUID       string                 `json:"call_uuid"`
	CalleeNumber   string                 `json:"callee_number"`
	GroupNumber    string                 `json:"group_number"`
	MiddleNumber   string                 `json:"middle_number"`
	Dtmf           string                 `json:"dtmf"`
	AdditionalData map[string]interface{} `json:"additional_data"`
}

// 定义响应结构体，符合 HTTPResponse 格式
type HTTPResponse struct {
	UUID              string                 `json:"uuid"`
	Caller            string                 `json:"caller"`
	Callee            string                 `json:"callee"`
	Action            string                 `json:"action"`
	ActionData        map[string]string      `json:"action_data"`
	AfterBridge       string                 `json:"after_bridge"`
	AfterBridgeData   string                 `json:"after_bridge_data"`
	DtmfLen           int                    `json:"dtmf_len"`
	DtmfAudio         string                 `json:"dtmf_audio"`
	DtmfBadAudio      string                 `json:"dtmf_bad_audio"`
	UseSurvey         bool                   `json:"use_survey"`
	BridgeFailRing    string                 `json:"bridge_fail_ring"`
	WaitForAnswerRing string                 `json:"wait_for_answer_ring"`
	TransferRing      string                 `json:"transfer_ring"`
	SurveyRing        []string               `json:"survey_ring"`
	AssociateData     map[string]interface{} `json:"associate_data"`
}
type DbConnector struct {
	DB *sql.DB
}

func initConnection(dbType, connectionString string) *DbConnector {
	//postgresql
	/*
			<param name="db_type" value="postgres"/>
		    <param name="db_string" value="postgres://postgres:Nway2017@127.0.0.1/cloudcc_web?sslmode=disable"/>
	*/
	//mysql
	/*
			<param name="db_type" value="mysql"/>
		    <param name="db_string" value="root:Nway2017@tcp(127.0.0.1:3306)/cloudcc_web"/>
	*/
	conn, err := sql.Open(dbType, connectionString)
	if err != nil {
		fmt.Println("Failed to initialize connection:", err)
		return nil
	}

	if err := conn.Ping(); err != nil {
		fmt.Println("Failed to ping database:", err)
		return nil
	}

	return &DbConnector{DB: conn}
}

// 处理 HTTP 请求并构建响应
func httpCallFlowHandler(w http.ResponseWriter, r *http.Request) {
	var eventRequest EventRequest

	// 解析请求体中的 JSON 数据
	// 读取并打印请求体内容
	bodyBytes, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read request body", http.StatusInternalServerError)
		return
	}
	bodyString := string(bodyBytes)
	fmt.Println("received json as string:", bodyString)

	// 重置 r.Body 以便后续解析
	r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
	if err := json.NewDecoder(r.Body).Decode(&eventRequest); err != nil {
		http.Error(w, "Invalid request payload", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()
	var response HTTPResponse
	// 创建 HTTPResponse 并填充字段
	if eventRequest.GroupNumber == "120" {
		response = HTTPResponse{
			UUID:   eventRequest.CallUUID,
			Caller: eventRequest.CallerNumber,
			Callee: eventRequest.CalleeNumber,
			Action: "bridge",
			ActionData: map[string]string{
				"ad_number":         "10002",
				"ad_gateway":        "",
				"ad_display_number": eventRequest.CallerNumber,
				"ad_timeout":        "30",
				"ad_data":           "",
			},
			AfterBridge:       "playback",
			AfterBridgeData:   "10086",
			UseSurvey:         true,
			BridgeFailRing:    "bridge_fail_ring.wav",
			WaitForAnswerRing: "wait_for_answer_ring.wav",
			TransferRing:      "transfer_ring.wav",
			AssociateData:     eventRequest.AdditionalData,
		}
	} else if eventRequest.GroupNumber == "110" {
		response = HTTPResponse{
			UUID:          eventRequest.CallUUID,
			Caller:        eventRequest.CallerNumber,
			Callee:        eventRequest.CalleeNumber,
			Action:        "dtmf",
			DtmfLen:       2,
			DtmfAudio:     "/home/ivr.wav",
			DtmfBadAudio:  "/home/ivr_bad.wav",
			AssociateData: eventRequest.AdditionalData,
		}
	}else if eventRequest.GroupNumber == "119" {
		response = HTTPResponse{
			UUID:          eventRequest.CallUUID,
			Caller:        eventRequest.CallerNumber,
			Callee:        eventRequest.CalleeNumber,
			Action:        "hangup",
			ActionData: map[string]string{
				"ad_rings":          "goodbye.wav",
			}, 
			AssociateData: eventRequest.AdditionalData,
		}
	}else if eventRequest.GroupNumber == "122" {
		response = HTTPResponse{
			UUID:          eventRequest.CallUUID,
			Caller:        eventRequest.CallerNumber,
			Callee:        eventRequest.CalleeNumber,
			Action:        "playback",
			ActionData: map[string]string{
				"ad_rings":          "alice.wav",
			}, 
			AssociateData: eventRequest.AdditionalData,
		}
	}

	// 将响应序列化为 JSON
	responseJSON, err := json.Marshal(response)
	if err != nil {
		http.Error(w, "Failed to build response JSON", http.StatusInternalServerError)
		return
	}
	//fmt.Println("received:", eventRequest)
	fmt.Println("sent:", string(responseJSON))
	// 设置响应头和状态码
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(responseJSON)
}

// 新的处理器函数，用于接收 extension 事件状态
func pushEventHandler(w http.ResponseWriter, r *http.Request) {
	var eventRequest EventRequest

	// 解析请求体中的 JSON 数据
	bodyBytes, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read request body", http.StatusInternalServerError)
		return
	}
	bodyString := string(bodyBytes)
	fmt.Println("received json event as string:", bodyString)

	// 重置 r.Body 以便后续解析
	r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
	defer r.Body.Close()
	if err := json.NewDecoder(r.Body).Decode(&eventRequest); err != nil {
		http.Error(w, "Invalid request payload", http.StatusBadRequest)
		return
	}
	fmt.Println("From ip:", r.RemoteAddr)
	//fmt.Println("Extension Event:", eventRequest)

	// 响应成功
	w.WriteHeader(http.StatusOK)
}

func main() {
	// 解析启动参数
	portFlag := flag.String("port", "", "Port to listen on")
	flag.Parse()

	// 尝试从配置文件中读取端口
	cfg, err := ini.Load("config.cfg")
	if err != nil {
		log.Fatalf("Failed to read config file: %v", err)
	}

	port := cfg.Section("server").Key("port").String()
	if *portFlag == "" {
		PORT = ":" + port
	} else {
		PORT = *portFlag
	}

	// 设置 HTTP 路由和处理器
	http.HandleFunc("/call_flow", httpCallFlowHandler)
	http.HandleFunc("/push_events", pushEventHandler)
	// 启动 HTTP 服务器
	fmt.Printf("Starting server on %s\n", PORT)
	log.Fatal(http.ListenAndServe(PORT, nil))
}
